/* Copyright 2018-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package com.demo;

import static com.github.drinkjava2.jsqlbox.JSQLBOX.gctx;

import java.sql.Connection;

import com.alibaba.fastjson.JSON;
import com.demo.page.Pages.emptyPage;
import com.demo.page.Pages.errorPage;
import com.github.drinkjava2.gosqlgo.ServletTemplate;
import com.github.drinkjava2.jtransactions.tinytx.TinyTxConnectionManager;
import com.github.drinkjava2.jwebbox.WebBox;

/**
 * This is the super class of JavaTemplate and QryTemplate, to store servlet
 * environment info. currently version GoSqlGO depends on JSP .
 * 
 * @author Yong Zhu
 * @since 1.0.0
 */
@SuppressWarnings("all")
public abstract class DaoTemplate extends ServletTemplate {

	@Override
	public WebBox run() {
		initParams();
		Object result = null;
		if (!tx)
			try {
				result = execute();
			} catch (Exception e) {
				e.printStackTrace();
				return new emptyPage();
			}
		else { // open transaction
			TinyTxConnectionManager tx = (TinyTxConnectionManager) gctx().getConnectionManager();
			try {
				tx.startTransaction(gctx().getDataSource(), Connection.TRANSACTION_READ_COMMITTED);
				result = execute();
				tx.commit(gctx().getDataSource());
			} catch (Exception e) {
				try {
					tx.rollback(gctx().getDataSource());
				} catch (Exception e1) {
				}
				e.printStackTrace();
				return new errorPage();
			}
		}
		if (result == null)
			return new WebBox().setText("null");
		if (result instanceof String)
			return new WebBox().setText((String) result);
		if (result instanceof WebBox)
			return (WebBox) result;
		return new WebBox().setText(JSON.toJSONString(result));
	}

}
